package xp2p.global;
import java.util.HashMap;
import java.util.LinkedList;

import net.jxta.peer.PeerID;

public class PeersAndJobs
{
	private Object sync = new Object();

	public HashMap<PeerID, LinkedList<Integer>> peersToJobs = new HashMap<PeerID, LinkedList<Integer>>();

	public HashMap<Integer, LinkedList<PeerID>> jobsToPeers = new HashMap<Integer, LinkedList<PeerID>>();

	public void Add(PeerID peer, Integer job)
	{
		synchronized (sync)
		{
			LinkedList<Integer> list = peersToJobs.get(peer);
			if (list == null)
			{
				list = new LinkedList<Integer>();
			}
			if (!list.contains(job))
			{
				list.add(job);
			}
			peersToJobs.put(peer, list);
			LinkedList<PeerID> list1 = jobsToPeers.get(job);
			if (list1 == null)
			{
				list1 = new LinkedList<PeerID>();
			}
			if (!list1.contains(peer))
			{
				list1.add(peer);
			}
			jobsToPeers.put(job, list1);
		}
	}

	public Integer[] GetJobsFor(PeerID peer)
	{
		synchronized (sync)
		{
			return peersToJobs.get(peer).toArray(new Integer[0]);
		}
	}

	public PeerID[] GetPeersFor(Integer job)
	{
		synchronized (sync)
		{
			return jobsToPeers.get(job).toArray(new PeerID[0]);
		}
	}

	public void Delete(PeerID peer, Integer job)
	{
		synchronized (sync)
		{
			LinkedList<PeerID> list = jobsToPeers.get(job);
			if (list != null)
			{
				list.remove(peer);
			}
			LinkedList<Integer> list1 = peersToJobs.get(peer);
			if (list1 != null)
			{
				list1.remove(job);
			}
		}
	}
}
